import os
import shutil
import threading
import time
import traceback

import guizero
from PIL import Image

from frame import MyAPP


class GifPic(MyAPP):
    '继承MyAPP'

    def __init__(self, title='动图大师'):
        MyAPP.__init__(self)

    def loadsettings(self):
        '加载配置文件'
        if os.path.isfile(self.setupPath):
            settings = self.readCsv()
        else:
            settings = [
                ['标题', '', '动图大师'],
                ['是否预览动图', '是,否', '是'],
            ]
            self.writeCsv(settings)
        self.app.title = settings[0][2]
        return settings

    def drawMyApps(self):
        '这里绘制你要用的模块'
        box = guizero.Box(self.app, height='fill', width='fill', layout='grid')
        box1 = guizero.Box(box, border=1, width=400, height=400, grid=[0, 0])
        box2 = guizero.Box(box, border=1, width=400, height=400, grid=[1, 0])
        self.oldPic = guizero.Picture(box1, image=None, width=400, height=400)
        self.newPic = guizero.Picture(box2, image=None, width=400, height=400)
        box3 = guizero.Box(box, layout='grid', grid=[0, 1])
        guizero.PushButton(box3, command=self.openGif,
                           text='打开图片', grid=[2, 0], pady=1)
        guizero.Text(box3, text='项目名称', grid=[0, 0])
        self.projectTextBox = guizero.TextBox(box3, text='', grid=[1, 0])
        self.cutButton = guizero.PushButton(
            box3, command=self.cutGif, text='分割图片', grid=[3, 0], enabled=False, pady=1)
        box4 = guizero.Box(box, layout='grid', grid=[1, 1])
        guizero.Text(box4, text='设置速度(ms)', grid=[0, 0])
        self.delayTimeBox = guizero.TextBox(box4, text='100', grid=[1, 0])
        guizero.PushButton(box4, command=self.openFolder,
                           text='设置素材目录', pady=1, grid=[2, 0])
        self.createButton = guizero.PushButton(
            box4, command=self.createGif, text='创建图片', grid=[3, 0], enabled=False, pady=1)

    def openGif(self):
        '打开gif图片'
        gifPath = guizero.select_file(
            title='选择gif图片', filetypes=[['gif图片', '*.gif']])
        if gifPath != '':
            self.oldPic.image = gifPath
            self.gifPath = gifPath
            self.cutButton.enable()

    def cutGif(self):
        '分割图片'
        self.projectName = self.projectTextBox.value
        if self.projectName == '':
            self.projectName = str(int(time.time()))
        self.projectPath = os.path.join(self.path, self.projectName)
        if os.path.isdir(self.projectPath):
            shutil.rmtree(self.projectPath)
        os.mkdir(self.projectPath)
        image = Image.open(self.gifPath)
        i = -1
        while True:
            try:
                i += 1
                image.seek(i)
                image.save(os.path.join(self.projectPath, str(i)+'.png'))
            except:
                # traceback.print_exc()
                # print(f'第{i}张图片拆分失败')
                break
        guizero.info('提示', f'拆分成功\n共拆解图像帧数：{i}')

    def openFolder(self):
        '打开资源目录'
        self.sourcePath = guizero.select_folder('选择资源')
        if self.sourcePath != '':
            self.createButton.enable()
            self.images = []
            files = os.listdir(self.sourcePath)
            a = []
            for file in files:
                filePath = os.path.join(self.sourcePath, file)
                if os.path.isfile(filePath):
                    if filePath.endswith('.png'):
                        a.append(int(file.split('.')[0]))
            a.sort()
            for i in a:
                im = Image.open(os.path.join(self.sourcePath, f'{i}.png'))
                self.images.append(im)
            if self.settings[1][2] == '是':
                self.t = threading.Thread(target=self.previewGif)
                self.t.start()

    def createGif(self):
        '创建gif图片'
        name = os.path.join(self.sourcePath, '动图.gif')
        delayTime = self.delayTimeBox.value
        try:
            delayTime = int(delayTime)
        except:
            delayTime = 100
        try:
            im = self.images[0]
            im.save(name, save_all=True,
                    append_images=self.images[1:], duration=delayTime, loop=0)
            guizero.info('提示', f'恭喜你，动图创建成功！保存在：\n{name}')
        except:
            traceback.print_exc()
            guizero.warn('错误', '抱歉动图创建失败！')

    def previewGif(self):
        '预览图片'
        i = 0
        self.end = 0
        while True:
            delayTime = self.delayTimeBox.value
            try:
                delayTime = int(delayTime)
            except:
                delayTime = 100
            delayTime /= 1000
            time.sleep(delayTime)
            self.newPic.image = self.images[i]
            i += 1
            if i == len(self.images):
                i = 0
            if self.end:
                break

    def close(self):
        self.setupPath = os.path.join(self.path, 'setup.csv')
        try:
            self.saveSettings()
        except AttributeError:
            print('设置未变更，所以不用保存。')
        finally:
            self.end = 1
            time.sleep(0.1)
            self.app.destroy()


if __name__ == '__main__':
    app = GifPic()
    app.display()
